package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.web.tags.UserTag;
import org.apache.xpath.objects.XNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.*;
import java.io.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
     private  RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Override
    public TablePageInfo< BpmnInfo > query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    /**
     * 1创建时间是后台来完成添加的
     * 2日期无法封装 实体类贴注解@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
     * 3实际到店时间是不用填写的
     * @param bpmnInfo
     */
    @Override
    public void save(BpmnInfo bpmnInfo) {
        BpmnInfo newBpmnInfo = new BpmnInfo();
        newBpmnInfo.setInfo(bpmnInfo.getInfo());
        bpmnInfoMapper.insert(newBpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        BpmnInfo dbApponitment = this.get(bpmnInfo.getId());

        dbApponitment.setInfo(bpmnInfo.getInfo());
        bpmnInfoMapper.updateByPrimaryKey(dbApponitment);
    }

    @Override
    public void deleteBatch(Long[] ids) {
        //Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : ids) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List< BpmnInfo > list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public String updateBpmn(MultipartFile file) throws IOException {
        String extension = FileUploadUtils.getExtension(file);
        String path=null;
        if (!"bpmn".equals(extension)){
            //获取文件上传的保存路径返回给浏览器
            throw new BusinessException("请选择bpmn格式文件");
        }
        path= FileUploadUtils.upload(SystemConfig.getProfile(), file);
        String  pathAndFileName = path +","+ file.getOriginalFilename();
        return pathAndFileName;
    }
    //涉及到多个表加个事务
    @Transactional
    @Override
    public void depoly(String pathAndFileName, String info, String bpmnType) throws IOException {
        String[] split = pathAndFileName.split(",");
        String path = split[0];
        System.out.println(split[1]);
        System.out.println(path);
        File file = new File(SystemConfig.getProfile(),path);
        FileInputStream fileInputStream = new FileInputStream(file);


        Deployment deployment = repositoryService.
                createDeployment().
                addInputStream(path, fileInputStream).
                deploy();

        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setInfo(info);
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setDeploymentId(deployment.getId());
        bpmnInfo.setDeployTime(deployment.getDeploymentTime());
        ProcessDefinition processDefinition = repositoryService.
                createProcessDefinitionQuery().
                deploymentId(deployment.getId()).
                singleResult();
        bpmnInfo.setBpmnName(processDefinition.getName());
/*

        BpmnInfo uniqueBpmnInfo =  bpmnInfoMapper.queryprocessDefinitionkey(processDefinition.getKey());
        if (uniqueBpmnInfo !=null){
           repositoryService.deleteDeployment(processDefinition.getDeploymentId());
           throw new BusinessException("亚兴你还来,小心搞你哦");
        }
*/

        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfoMapper.insert(bpmnInfo);
        fileInputStream.close();
    }
    @Transactional
    @Override
    public void delete(Long id) {
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);
        bpmnInfoMapper.deleteByPrimaryKey(id);
        /**
         * 检查顶一下是否有流程实例,拿到流程实例中的BusinessKey,然后把状态修改为初始化状态
         */

       //查询流程定义
        ProcessDefinition processDefinition = repositoryService.
                createProcessDefinitionQuery().
                deploymentId(bpmnInfo.getDeploymentId()).
                singleResult();
        List< ProcessInstance > list = runtimeService.
                createProcessInstanceQuery().
                deploymentId(bpmnInfo.getDeploymentId()).
                list();

        if (list.size()>0) {
            for (ProcessInstance processInstance : list) {
                String businessKey = processInstance.getBusinessKey();
                //一定要先查询数据再进行删除数据,否则就会报空指针
                CarPackageAudit carPackageAudit = carPackageAuditMapper.
                        selectByPrimaryKey(Long.valueOf(businessKey));
                carPackageAuditMapper.deleteByPrimaryKey(Long.valueOf(businessKey));

                ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(carPackageAudit.getServiceItemId());
                //在两个interger类型的数据比较时需要注意应该使用equels而不是==或!=毕竟他们本质比较的是地址,保险起见还是使用equels
                if (!serviceItem.getAuditStatus().equals(ServiceItem.AUDITSTATUS_APPROVED)){
                    serviceItemMapper.updateAuditStatus(serviceItem.getId(),ServiceItem.AUDITSTATUS_INIT);
                }
            }
        }

        //删除ativiti内部表,BUDA
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(),true);
        //删除部署文件,processDefinition.getResourceName() 获取的是bpmn文件的路径,拼接系统路径
        File file = new File(SystemConfig.getProfile(),processDefinition.getResourceName());
        if (file.exists()) {
            file.delete();
        }

    }

    /**
     *
     * @param deploymentId 获取流程定义
     * @param type 通过类型来判断是什么文件然后使用响应额api获取相应的文件,xml或中png
     * @return
     */
    @Override
    public InputStream readResources(String deploymentId, String type) {
        InputStream inputStream =null;
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        if ("xml".equals(type)) {

            inputStream= repositoryService.
                   getResourceAsStream(deploymentId, processDefinition.getResourceName());

        }else{
            DefaultProcessDiagramGenerator defaultProcessDiagramGenerator = new DefaultProcessDiagramGenerator();
            /***
             * 需要三个参数
             * bpmnModel信息
             * 第二个参数高亮节点信息
             * 第三个高亮连线节点集合
             */
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            inputStream = defaultProcessDiagramGenerator.generateDiagram(
                    bpmnModel,
                    Collections.EMPTY_LIST,
                    Collections.EMPTY_LIST,
                    //加入宋体否则乱码
                    "宋体",
                    "宋体",
                    "宋体"
            );
        }
        return inputStream;
    }

    @Override
    public  BpmnInfo queryByNameType(String carPackage) {

        List< BpmnInfo > bpmnInfos = bpmnInfoMapper.selectByNameType(carPackage);
        //当部署流程被删除后就没有会报越界异常
        if (bpmnInfos.size()==0){
            throw  new BusinessException("流程不存在,请重新部署流程");
        }
        return bpmnInfos.get(0);
    }
}
